import { request } from "../../utils/request"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userLocation: {
      province: "", //省份
      city: "", //城市
      district: "", //地区
      town: "", //街道
      landmark: "" //地标
    },
    isLocation: false, //是否显示定位视图
    formData: {
      name: "",
      phone: "",
      province: "", //省份
      city: "", //城市
      district: "", //地区
      town: "", //街道
      landmark: "", //地标
      isDefault: "0" //默认地址 0不选中，1选中
    },
    region: [] //级联选择 省市区街道
  },

  /**
   * 加载用户当前定位
   */
  loadUserLocation() {
    wx.getLocation({
      type: 'wgs84',
      success: async (res) => {
        const latitude = res.latitude;  // 纬度
        const longitude = res.longitude;  // 经度
        const { token } = wx.getStorageSync("user")
        request({ url: "/address/getUserLocation/", method: "GET", data: { latitude, longitude }, header: { "Authorization": token } }).then(res => {
          this.setData({
            userLocation: res.data.data,
            isLocation: true
          })
        })
      }
    })
  },

  /**
   * 处理使用当前定位事件
   */
  handlerUseCurrent() {
    const { province, city, district, town, landmark } = this.data.userLocation;
    let newFormData = this.data.formData;
    newFormData.province = province
    newFormData.city = city
    newFormData.district = district
    newFormData.town = town
    newFormData.landmark = landmark
    this.setData({
      formData: newFormData,
      region: [province, city, district, town]
    })
  },

  /**
   * 输入框值更改事件
   */
  handlerInput(e) {
    //获取当前是哪个input框触发的值修改
    const prop = e.currentTarget.dataset.prop
    //获取目前的表单数据
    let newFormData = this.data.formData
    //获取输入框的内容
    const value = e.detail.value
    //更新表单的数据
    newFormData[prop] = value
    this.setData({
      formData: newFormData
    })
  },

  /**
   * 省市区街道选择事件
   */
  handlerRegionChange(e) {
    //获取用户选中的数据，默认是一个数组，分别是省市区街道
    const region = e.detail.value;
    //更新表单数据
    let newFormData = this.data.formData
    newFormData.province = region[0]
    newFormData.city = region[1]
    newFormData.district = region[2]
    newFormData.town = region[3]
    //设置数据
    this.setData({
      region: region,
      formData: newFormData
    })
  },

  /**
   * 处理默认地址事件
   */
  handlerDefaultChange(e) {
    let newFormData = this.data.formData
    newFormData.isDefault = e.detail.value ? "1" : "0"
    this.setData({
      formData: newFormData
    })
  },

  /**
   * 腾讯地图选择用户地址
   */
  mapAddressChoose() {
    wx.chooseLocation({
      success: (res) => {
        //选定位置的地标名
        const landmark = res.name
        //选定位置的纬度
        const latitude = res.latitude
        //选定位置的经度 
        const longitude = res.longitude
        //发送请求，获取用户当前经纬度所在的地区信息
        const { token } = wx.getStorageSync("user")
        request({ url: "/address/getUserLocation/", method: "GET", data: { latitude, longitude }, header: { "Authorization": token } }).then(res => {
          //设置最新数据
          const { province, city, district, town } = res.data.data;
          let newFormData = this.data.formData;
          newFormData.province = province
          newFormData.city = city
          newFormData.district = district
          newFormData.town = town
          newFormData.landmark = landmark
          this.setData({
            formData: newFormData,
            region: [province, city, district, town]
          })
        })
      }
    })
  },

  /**
   * 处理表单提交
   */
  async handlerFormSubmit() {
    const formData = this.data.formData
    const { name, phone, province, city, district, town, landmark } = formData;
    if (!name || name.length > 10) {
      wx.showToast({ title: "收件人姓名不少于1个字，最多10个", icon: "none" });
      return;
    }
    if (!phone || !/^1(3|4|5|7|8)\d{9}$/.test(phone)) {
      wx.showToast({ title: "电话号码格式不正确", icon: "none" });
      return;
    }
    if (!province || !city || !district || !town) {
      wx.showToast({ title: "请选择收件地区", icon: "none" });
      return;
    }
    if (!landmark || landmark.length < 2 || landmark.length > 50) {
      wx.showToast({ title: "详细地址不少于2个字，最多50个", icon: "none" });
      return;
    }
    //发送保存请求，如果表单包含id数据，则是修改操作，否则是新增操作
    const requestUrl = this.data.formData.id ? "/address/update/" : "/address/insert/"
    const { token } = wx.getStorageSync("user")
    const res = await request({ url: requestUrl, method: "POST", data: this.data.formData, header: { "Authorization": token } })
    if (res.data.state === 0) {
      wx.showToast({
        title: "保存成功",
        mask: true,
        success: () => {
          setTimeout(function () {
            //获取当前的页面跳转栈
            const pages = getCurrentPages();
            //获取上一个页面的对象
            const prevPage = pages[pages.length - 2];
            //重置上一个页面的数据
            prevPage.setData({
              addressList: [], //地址列表
              page: 1, //当前页
              pageSize: 5, //每页记录数
              totalPage: 0 //页数
            })
            //重新加载数据
            prevPage.onLoad()
            //返回到上一个页面
            wx.navigateBack({
              delta: 1
            })
          }, 1500)
        }
      })
    } else {
      wx.showToast({ title: res.data.message, icon: "none" });
    }
  },

  /**
   * 加载编辑地址
   */
  async loadEditAddress(addressId) {
    const { token } = wx.getStorageSync("user")
    const res = await request({ url: `/address/detail/${addressId}`, method: "GET", header: { "Authorization": token } })
    if (res.data.state === 0) {
      const addressData = res.data.data
      this.setData({
        formData: addressData,
        region: [addressData.province, addressData.city, addressData.district, addressData.town]
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    //获取用户当前定位
    this.loadUserLocation()
    //获取跳转过来时的收货地址id
    const { addressId } = options
    //如果有收货地址id意味着是编辑修改操作，没有收货id就是新增操作
    if (addressId) {
      //查询地址数据，并渲染至页面
      this.loadEditAddress(addressId)
    }
  }
})